package servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import business.BusinessEvent;
import business.BusinessUser;
import domain.Event;
import domain.User;

/**
 * Servlet implementation class EventController
 */
@WebServlet("/EventController")
public class EventController extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public EventController() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		newEventRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		newEventRequest(request, response);
	}

	private void newEventRequest(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
	    String eventName = request.getParameter("Nombre evento");
	    String eventDescription = request.getParameter("Descripcion");
	    String fecha = request.getParameter("fecha");
	    String hora = request.getParameter("hora");
	    HttpSession session = request.getSession();
	    User sessionUser = (User) session.getAttribute("session.user");
	    
	    Map<String,String> friendsInvited = new HashMap<String, String>();
	    if(request.getParameterValues("friends")!=null)
	    {
			String [] a = request.getParameterValues("friends");
			if(eventName != "" && eventDescription != "" && fecha!=null && hora!=null){
		    	for(int i=0;i<a.length;i++){
					User friend = BusinessUser.getUserById(new Integer(a[i]));
					friendsInvited.put(friend.getLogin(), "Sin confirmar");
				}
		    	Event newEvent = new Event(sessionUser.getLogin(), eventName, eventDescription, friendsInvited,fecha+" "+hora+":00");
		    	BusinessEvent.createEvent(newEvent); 
		    	Integer idLastEvent = BusinessEvent.getLastCreatedEvent();
		    	request.setAttribute("idLastEvent", idLastEvent);
		    	RequestDispatcher d = request.getRequestDispatcher("event.jsp");
				d.forward(request,response);
			}else{
		    	 response.sendRedirect("event_creation_error.html");
		    }
	    }
	    else
	    {
	    	response.sendRedirect("event_creation_error.html");
	    }
	}
}
